<script setup lang="ts">
import type { IConversation, IConversationRelation, ICustomer } from "@src/types";
import Conversation from "./Conversation.vue";
import { computed, ref } from "vue";
import { conversations } from "@src/store/defaults";
import useServiceStore from "@src/store/serviceStore";
import useStore from "@src/store/store";


const serviceStore = useServiceStore()
const store = useStore()
const conversationRelations = computed(()=>{
  if(serviceStore.conversationRelations){
    const keys = Object.keys(serviceStore.conversationRelations);
    keys.sort(function(a,b){return parseInt(a) - parseInt(b);});
    const sorted:IConversationRelation[] = [];
    keys.forEach(key => {
      const cr = serviceStore.conversationRelations[key];
      console.log(cr)
      if (serviceStore.showComplete && cr.status == 1) {
        sorted.push(cr);  
      }else if (!serviceStore.showComplete && cr.status == 0){
        sorted.push(cr);  
      }
    });
    return sorted;
  }else{
    return [];
  }
})




const toarry = computed(()=>(conversations:Record<string,IConversation>)=>{
  if(conversations && Object.keys(conversations).length > 0){
    const keys = Object.keys(conversations);
    keys.sort(function(a,b){return parseInt(a) - parseInt(b);});
    const sorted:IConversation[] = [];
    keys.forEach(key => {
      sorted.push(conversations[key]);
    });
    return sorted;
  }else{
    return [];
  }
});

const handleConversationChange = (conversationRelationId: number) => {
  serviceStore.currentConversationRelationId = conversationRelationId;
  var relation = serviceStore.conversationRelations[conversationRelationId];
  if (relation == undefined) {
    relation = serviceStore.conversationRelationsHistory[conversationRelationId];
  }
  relation.hasNew = false;
  store.conversationOpen = "open";
};

</script>

<template>  
  <div>
    <Conversation
      v-for="relation in conversationRelations"
      :relation="relation"
      :conversations="toarry(relation.conversations)"
      :key="relation.id"
      role="listitem"
      :handle-conversation-change="handleConversationChange"
      :is-active="serviceStore.currentConversationRelationId === relation.id"
    />
  </div>
</template>
